import 'dart:io';

import 'package:eshi/main.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:eshi/app/shi/data/parse/FileParser.dart';

class ImageWidget{
  static BuildContext? _context;
  static initContext(c){
    _context = c;
  }
  static Widget loadUrl(uri) {
      return  Image.network(
        uri,  // 示例图片 URL
        // width: 200,
        // height: 200,
        fit: BoxFit.cover,  // 图片填充方式
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return CircularProgressIndicator(  // 加载指示器
            value: loadingProgress.expectedTotalBytes != null
                ? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
                : null,
          );
        },
        errorBuilder: (context, error, stackTrace) {
          return Icon(Icons.error);  // 错误显示
        },
      );
  }
  static Widget load(String name,[Widget? children]) {
    var r = RegExp(r"(.+)_(\d+)x(\d+)$");
    double? w=200;
    double? h=null;
    if(r.hasMatch(name)){
        RegExpMatch m = r.firstMatch(name)!;
        name = m.group(1)!;
        w = (m.group(2) != '0') ?  double.parse(m.group(2)!) : null;
        h = (m.group(3)!='0') ?  double.parse(m.group(3)!) : null;
    }
    var uri = FileParser.getImage(name);
    if(uri.isNotEmpty){
      if(kIsWeb){
         return enlargeEnable(
          children ?? Image.asset(
              uri,   // 图片路径  
              width: w,
              height: h,
              fit: BoxFit.contain,
            )
          ,Image.asset(
            uri,   // 图片路径  
            fit: BoxFit.contain,
          ),name);
      }

      return enlargeEnable(
          children ?? Image.file(
              
              File(uri),   // 图片路径  
              width: w,
              height: h,
              fit: BoxFit.contain,
            )

          ,Image.file(
            File(uri),   // 图片路径  
            fit: BoxFit.contain,
          ),name);
    }else{
      return Text("img."+name);
    }
  }
  
  static Widget enlargeEnable(Widget child,Widget childBig, name){
    return GestureDetector(
          onTap:() {
            showDialog(
              context: _context!,
              builder: (BuildContext context) {
                return Dialog(
                  backgroundColor: Colors.transparent, // 透明背景
                  child: childBig
                );
              },
            );
          },
          onLongPress: (){
            customWidgetKey.currentState?.tabState?.onChangeName("audio",name);
          },
          child:child
    );
  }

}